package com.example.pages;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.testng.collections.Lists;

import com.example.tests.SortedListOf;
import com.example.tests.User;

public class ManagementPage extends InternalPage {

	@FindBy(xpath = "//form[@id='form']/table/tbody/tr/td[2]/input")
	public WebElement userNameField;
	
	@FindBy(xpath = "//form[@id='form']/table/tbody/tr[2]/td[2]/input")
	public WebElement emailField;
	
	@FindBy(xpath = "//form[@id='form']/table/tbody/tr[3]/td[2]/input")
	public WebElement passwordField;
	
	@FindBy(xpath = "//form[@id='form']/table/tbody/tr[4]/td[2]/input")
	public WebElement password2Field;
	
	@FindBy(xpath = "//form[@id='form']/table/tbody/tr[6]/td[2]/input")
	public WebElement saveButton;

	@FindBy(xpath = "//form[@id='form']/table/tbody/tr[6]/td[2]/input")
	public WebElement errorMessage;
		
	public boolean thereIsErrorMessage() {
		return errorMessage.isDisplayed();
	}

	@FindBy(css = "div#user-list table > tbody > tr")
	public List<WebElement> userRows;
	
	public ManagementPage createNewUser(User user) {
		userNameField.sendKeys(user.name);
		emailField.sendKeys(user.email);
		passwordField.sendKeys(user.password);
		password2Field.sendKeys(user.password);
		saveButton.click();
		return MyPageFactory.getPage(driver, ManagementPage.class);
	}

	public SortedListOf<User> getUsers() {
		List<User> users = Lists.newArrayList();
		for (WebElement row : userRows) {
			users.add(convertRowToUser(row));
		}
		return new SortedListOf<User>(users);
	}

	private User convertRowToUser(WebElement row) {
		List<WebElement> cells = row.findElements(By.tagName("td"));
		return new User()
		.withName(cells.get(1).getText())
		.withEmail(cells.get(2).getText());
	} 
	
	public ManagementPage deleteUser(User user) throws NoSuchElementException{
		try{
		for (WebElement row : userRows) {
			row.findElement(By.xpath("//td[6]/a/img")).click();
			driver.switchTo().alert().accept();
			break;
			}}
		catch (NoSuchElementException e) { 
			return null;
		}
		return MyPageFactory.getPage(driver, ManagementPage.class);
	}
}

